package com.macaline.framemarker.db;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 模拟数据库
 */
public class DBMap extends ADB implements IDB{

    /**
     * 数据库表
     */
    private Map<String, CopyOnWriteArrayList<Map<String, Object>>> db = new HashMap<String, CopyOnWriteArrayList<Map<String, Object>>>();


    @Override
    public List<Map<String, Object>> select(String tabName) {
        return db.get(tabName);
    }

    @Override
    public void dropTab(String tabName) {
        db.remove(tabName);
    }

    @Override
    public Integer update(String tabName, Map<String, Object> item) {
        return null;
    }

    @Override
    public Integer insert(String tabName, Map<String, Object> data) throws Exception{
        CopyOnWriteArrayList<Map<String, Object>> list = db.get(tabName);
        Object id = data.get("id");
        // 判断id是否重复
        if(id != null){
            for (Map<String, Object> item : list) {
                if(id.equals(item.get(id))){
                    throw new Exception("table " + tabName + " id not one");
                }
            }
        }
        return 1;
    }

    @Override
    public Integer deleteTab(String tabName) {
        CopyOnWriteArrayList<Map<String, Object>> list = db.get(tabName);
        if(list != null){
            db.remove(tabName);
            return list.size();
        }
        return 0;
    }

    /**
     * 获取表
     * @param tabName
     * @return
     */
    public List<Map<String, Object>> getTable(String tabName){
        return db.get(tabName);
    }

}
